<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>刺激提取工具</title>
    <style>
        html, body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
            overflow: auto;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #333;
            color: white;
            padding: 10px 20px;
            font-size: 18px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .video-path {
            background-color: #f1f8e9;
            padding: 6px 15px;
            margin-bottom: 8px;
            border-radius: 4px;
            border-left: 4px solid #689f38;
            word-break: break-all;
            width: 100%;
            max-width: 800px;
            box-sizing: border-box;
        }
        .video-path h2 {
            margin: 0 0 2px 0;
            color: #33691e;
            font-size: 20px;
        }
        .video-path p {
            margin: 0;
            font-family: monospace;
            font-size: 13px;
            overflow-wrap: break-word;
        }
        .content {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
            max-width: 100%;
            margin: 0 auto;
            overflow-y: auto;
        }
        .image-container {
            position: relative;
            margin: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            background-color: #fff;
            border-radius: 4px;
            overflow: hidden;
            max-width: 100%;
        }
        img {
            display: block;
            max-width: 100%;
            cursor: crosshair;
        }
        .point {
            position: absolute;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: red;
            border: 2px solid white;
            transform: translate(-50%, -50%);
            pointer-events: none;
            z-index: 10;
        }
        .instructions {
            margin: 10px;
            padding: 6px 15px;
            background-color: #e7f3fe;
            border-left: 4px solid #2196F3;
            border-radius: 4px;
            width: 100%;
            max-width: 800px;
            box-sizing: border-box;
        }
        .instructions h3 {
            margin: 5px 0;
            font-size: 14px;
        }
        .instructions p {
            margin: 5px 0;
            font-size: 13px;
        }
        .button-container {
            margin: 20px 0;
            width: 100%;
            max-width: 800px;
            display: flex;
            justify-content: center;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 4px;
            background-color: #4CAF50;
            color: white;
            cursor: pointer;
            margin: 0 5px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #cancelBtn {
            background-color: #f44336;
        }
        #cancelBtn:hover {
            background-color: #d32f2f;
        }
        .status-container {
            margin: 20px 0;
            padding: 15px;
            border-radius: 4px;
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            display: none;
            width: 100%;
            max-width: 800px;
            box-sizing: border-box;
        }
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border-left-color: #09f;
            display: inline-block;
            margin-right: 10px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .progress-bar {
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 4px;
            margin-top: 10px;
        }
        .progress {
            height: 20px;
            background-color: #4CAF50;
            border-radius: 4px;
            width: 0%;
            transition: width 0.3s;
            text-align: center;
            line-height: 20px;
            color: white;
        }
        .threshold-container {
            margin: 10px 0;
            width: 100%;
            max-width: 800px;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #e8f5e9;
            padding: 6px 15px;
            border-radius: 4px;
            border-left: 4px solid #4CAF50;
        }
        .threshold-input {
            margin: 5px 0;
            width: 100%;
        }
        .threshold-input label {
            display: block;
            margin-bottom: 3px;
            font-weight: bold;
            font-size: 13px;
        }
        .threshold-input input {
            width: 100%;
            padding: 6px 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
        }
        .threshold-container p {
            margin: 5px 0;
            font-size: 12px;
            font-style: italic;
        }
        
        /* 媒体查询，适配不同屏幕尺寸 */
        @media (max-width: 768px) {
            .instructions,
            .status-container,
            .button-container {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        刺激提取工具
    </div>
    <div class="content">
        <div class="video-path">
            <h2>当前处理视频：</h2>
            <p>{{ video_path }}</p>
        </div>
        <div class="instructions">
            <h3>使用说明：</h3>
            <p>请在图像上点击LED发光二极管的位置。系统将分析视频中每一帧该位置附近的亮度变化，判断是否存在刺激。</p>
        </div>
        <div class="threshold-container">
            <div class="threshold-input">
                <label for="thresholdValue">请设置亮度阈值（0-255，默认值：150）：</label>
                <input type="number" id="thresholdValue" min="0" max="255" value="150" step="1">
            </div>
            <p>说明：阈值越低，越容易检测到亮度变化；阈值越高，检测结果越严格。</p>
        </div>
        <div class="image-container">
            <img id="frameImage" src="data:image/jpeg;base64,{{ image_data }}" alt="视频第一帧">
            <div id="point" class="point" style="display: none;"></div>
        </div>
        <div class="status-container" id="processingStatus">
            <div class="spinner"></div>
            <span id="statusText">正在处理视频帧，请稍候...</span>
            <div class="progress-bar">
                <div class="progress" id="progressBar">0%</div>
            </div>
        </div>
        <div class="button-container">
            <button id="confirmBtn" disabled>确认选择</button>
            <button id="cancelBtn">关闭</button>
        </div>
    </div>

    <script>
        let selectedPoint = null;
        const frameImage = document.getElementById('frameImage');
        const pointMarker = document.getElementById('point');
        const confirmBtn = document.getElementById('confirmBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const processingStatus = document.getElementById('processingStatus');
        const statusText = document.getElementById('statusText');
        const progressBar = document.getElementById('progressBar');
        const thresholdInput = document.getElementById('thresholdValue');
        const taskId = "{{ task_id }}";
        let progressInterval = null;
        let naturalWidth, naturalHeight;
        
        // 图像加载完成后获取原始尺寸
        frameImage.onload = function() {
            naturalWidth = this.naturalWidth;
            naturalHeight = this.naturalHeight;
            console.log(`图像原始尺寸: ${naturalWidth}x${naturalHeight}`);
        };

        frameImage.addEventListener('click', function(e) {
            const rect = frameImage.getBoundingClientRect();
            const clickX = e.clientX - rect.left;
            const clickY = e.clientY - rect.top;
            
            // 计算点击位置相对于原始图像的坐标
            const displayWidth = frameImage.width || frameImage.clientWidth;
            const displayHeight = frameImage.height || frameImage.clientHeight;
            
            // 原始图像坐标 = (点击位置 / 显示尺寸) * 原始尺寸
            const originalX = Math.round((clickX / displayWidth) * naturalWidth);
            const originalY = Math.round((clickY / displayHeight) * naturalHeight);
            
            // 保存原始图像上的坐标
            selectedPoint = { x: originalX, y: originalY };
            
            console.log(`点击位置: 显示坐标(${clickX}, ${clickY}), 原始坐标(${originalX}, ${originalY})`);
            
            // 显示选择点
            pointMarker.style.left = clickX + 'px';
            pointMarker.style.top = clickY + 'px';
            pointMarker.style.display = 'block';
            
            // 启用确认按钮
            confirmBtn.disabled = false;
        });

        confirmBtn.addEventListener('click', function() {
            if (selectedPoint) {
                // 禁用按钮，防止重复点击
                confirmBtn.disabled = true;
                cancelBtn.disabled = true;
                
                // 显示处理状态
                showProcessing();
                
                // 发送选择的点
                fetch(`/task/extract_stimulus/select_point/${taskId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        x: selectedPoint.x,
                        y: selectedPoint.y,
                        threshold: parseInt(thresholdInput.value, 10) || 150
                    }),
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert('错误: ' + data.error);
                        cancelBtn.disabled = false;
                    } else {
                        // 开始轮询进度
                        pollProgress();
                    }
                })
                .catch(error => {
                    alert('请求错误: ' + error);
                    cancelBtn.disabled = false;
                });
            }
        });

        cancelBtn.addEventListener('click', function() {
            window.close();
        });

        function showProcessing() {
            frameImage.style.opacity = '0.5';
            processingStatus.style.display = 'block';
            
            // 确保滚动到进度条位置
            processingStatus.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }

        function pollProgress() {
            progressInterval = setInterval(() => {
                fetch(`/task/extract_stimulus/progress/${taskId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        clearInterval(progressInterval);
                        statusText.innerText = '处理出错: ' + data.error;
                        cancelBtn.disabled = false;
                        return;
                    }
                    
                    // 更新进度条
                    progressBar.style.width = data.percentage + '%';
                    progressBar.innerText = data.percentage + '%';
                    
                    // 更新状态文本
                    if (data.status === "Running") {
                        statusText.innerText = `正在处理视频帧，已完成 ${data.percentage}%...`;
                    } else if (data.status === "Completed") {
                        clearInterval(progressInterval);
                        statusText.innerText = '处理完成，正在返回结果...';
                        // 处理完成后关闭窗口
                        setTimeout(() => {
                            window.close();
                        }, 2000);
                    }
                })
                .catch(error => {
                    console.error('获取进度失败:', error);
                });
            }, 1000); // 每秒更新一次
        }
    </script>
</body>
</html> 